#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include<unordered_map> 
#include<vector>
#include<algorithm>
int w[10010];
int n;
using namespace std;
unordered_map<int, vector<int>> tree;
int countw(int i)
{
	int ret = w[i - 1];
	if (tree[i].size() == 0) return ret;
	else if (tree[i].size() == 1)
	{
		ret += countw(tree[i][0]);
	}
	else
	{
		ret += countw(tree[i][0]);
		ret += countw(tree[i][1]);
	}
	return ret;
}
int main() {

	cin >> n;
	for (int i = 0;i < n;i++) scanf("%d", &w[i]);
	int x, y;
	int m = n - 1;
	while (m--)
	{
		scanf("%d %d", &x, &y);
		tree[x].push_back(y);
	}
	int i = 1;
	int write_sum = 0;
	int red_sum = w[0];
	while (tree[i].size() == 2)
	{
		int left = countw(i * 2);
		int right = countw(i * 2 + 1);
		write_sum += max(left, right);
		if (left = max(left, right))
		{
			red_sum += w[tree[i][1] - 1];
			i = tree[i][1];
		}
		else
		{
			red_sum += w[tree[i][0]];
			i = tree[i][0];
		}
	}
	if (tree[i].size() == 1) write_sum += countw(tree[i][0]);
	cout << write_sum - red_sum;

	return 0;
}